<template>
  <el-select ref="selectorRef"
             :placeholder="placeholder"
             automatic-dropdown
             filterable
             clearable
             v-model="selected"
             @change="onSelectChange"
             @blur="onBlur"
  >
    <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value"
    />
  </el-select>
</template>

<script lang="ts" setup>
import {defineProps, defineEmits, ref, onBeforeMount, watch, onMounted} from 'vue'
import {listDept} from '@/api/system/dept'
const $emit = defineEmits([
  'update:modelValue',
  'change',
  'blur'
])

const props = defineProps({
  placeholder: {
    type: String,
    required: false,
    default: ''
  },
  modelValue: {
    type: Object,
    required: false
  },
  atChange: {
    type: Function,
    required: false
  }
})

const options = ref([])
const selectorRef = ref()
const selected = ref()

onBeforeMount(() => {
  onSearchRemoteDepart()
})

onMounted(() => {
  selected.value = props.modelValue
})

const onSearchRemoteDepart = () => {
  listDept().then(res => {
    if (res.data?.length) {
      options.value = res.data.map(item => Object.assign({label: item.deptName, value: item.deptId}))
    }
  })
}

const onBlur = (event) => {
  $emit('blur',  event)
}

const onSelectChange = () => {
  selectorRef.value.blur()
  const depart = options.value.find(item => item.value === selected.value)
  $emit('change', {
    deptId: selected.value,
    depart
  })
}

watch(() => props.modelValue, (newVal) => {
  selected.value = props.modelValue
})

watch(() => selected.value, (newVal) => {
  $emit('update:modelValue', newVal)
})
</script>